package org.example;

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.javatuples.Pair;
import org.javatuples.Triplet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.EnumSet;
import java.util.Map;

/**
 * 用途
 *
 * @author deng
 * @date 2022/1/22 10:05
 */
public class SsdCommand {



    public static Pair<String,String>  execCommand(SshClient client, String command) throws IOException {

        long timeout = 60000;
        // using the client for multiple sessions...
        try (ClientSession session = client.connect("root", "192.168.133.180", 22)
                .verify(timeout)
                .getSession()) {
            session.addPasswordIdentity("newlandedu@123"); // for password-based authentication
            // or
            // session.addPublicKeyIdentity(...key-pair...); // for password-less authentication
            // Note: can add BOTH password AND public key identities - depends on the client/server security setup

            session.auth().verify(timeout);
            // Assuming one has obtained a ClientSession as already shown
            try (ClientChannel channel = session.createExecChannel("kubectl get pods -n jhub")) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ByteArrayOutputStream err = new ByteArrayOutputStream();
                channel.setOut(out);
                channel.setErr(err);
                // ... spawn the thread(s) that will pump the STDIN/OUT/ERR
                try {
                    channel.open().verify( timeout);
                    // Wait (forever) for the channel to close - signalling shell exited
                    channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0L);
                    String result = out.toString();
                    String error = err.toString();
                    return Pair.with(result,error);

                } finally {
                    // ... stop the pumping threads ...
                }
            }
            // start using the session to run commands, do SCP/SFTP, create local/remote port forwarding, etc...
        }


    }

    public static void main(String[] args) throws IOException {

        SshClient client = SshClient.setUpDefaultClient();
        client.start();
        Pair<String, String> pair = execCommand(client, "kubectl get pods -n jhub");
        System.out.println("结果是" + pair.getValue0());
        client.stop();
    }
}
